/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * AnimalesExistentes.java
 *
 * Created on 28-nov-2011, 23:35:41
 */
package formularios;

import Reportes.MetodosImpresion;
import clases.*;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Elio
 */
public class AnimalesExistentes extends javax.swing.JDialog {

    /** Creates new form AnimalesExistentes */
    public AnimalesExistentes() {
        initComponents();
        this.setModal(true);
        String sql = DefinirConsultaSQL();
        CrearTabla(sql);
        lblMensaje.setText("Cantidad de animales: " + tablaanimales.getRowCount());

        //    new ConsultaAnimales().ListarAnimalesExistentes(jTable1);
    }

    public void Conectar() {
        try {
            db = new conexion();      //instancia de la clase conexion.java
            db.init();
            Connection conn = db.getMyConnection();
            stmt = conn.createStatement();
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Problemas al conectarse a la Base de Datos", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    private String DefinirConsultaSQL() {
        String consultasql = "";

        //Animales Existentes//
        if (cbFiltroAnimales.getSelectedIndex() == 0) {
            consultasql = "Select b.identificacion, b.idjose as 'N Manejo', b.numerofuego as 'N Fuego', b.NumSenasa as 'N Senasa', "
                    + "b.fechaaplicacion as 'Fecha caravaneada', b.sexo as 'Sexo',b.anionacimiento as 'Año nacimiento', p.descripcion as 'Pelaje', tb.descripcion as 'Categoria', b.ColorCaravana as 'Color caravana' "
                    + "from  bovino b, tipobovino tb, pelaje p "
                    + "where  b.idtipobovino = tb.idtipobovino and b.idpelaje = p.idpelaje and b.idtag <> '' "
                    + "order by idjose";
            
        //Animeles Vendidos//
        } else if (cbFiltroAnimales.getSelectedIndex() == 1) {
            consultasql = "Select b.identificacion, b.idjose as 'N Manejo', b.numerofuego as 'N Fuego', b.NumSenasa as 'N Senasa', "
                    + "b.fechaaplicacion as 'Fecha caravaneada', b.sexo as 'Sexo',b.anionacimiento as 'Año nacimiento', p.descripcion as 'Pelaje', tb.descripcion as 'Categoria', b.ColorCaravana as 'Color caravana' "
                    + "from  bovino b, tipobovino tb, pelaje p "
                    + "where  b.idtipobovino = tb.idtipobovino and b.idpelaje = p.idpelaje and b.idtag = '' "
                    + "order by idjose";
        }else {
            if (cbFiltroAnimales.getSelectedIndex() < 7) {
                String Color = cbFiltroAnimales.getSelectedItem().toString().substring(9);
                consultasql = "Select b.identificacion, b.idjose as 'N Manejo', b.numerofuego as 'N Fuego', b.NumSenasa as 'N Senasa', "
                        + "b.fechaaplicacion as 'Fecha caravaneada', b.sexo as 'Sexo', b.anionacimiento as 'Año Nacimiento', p.descripcion as 'Pelaje', tb.descripcion as 'Categoria' "
                        + "from  bovino b, tipobovino tb, pelaje p "
                        + "where  b.idtipobovino = tb.idtipobovino and b.idpelaje = p.idpelaje and colorcaravana = '" + Color + "' and b.idtag <> '' "
                        + "order by idjose";
            } else {
                if (cbFiltroAnimales.getSelectedIndex() >= 7) {
                    String Desc = cbFiltroAnimales.getSelectedItem().toString();

                    int tipo = Integer.parseInt(new abmBovino().GetTipoBovino(Desc));
                    System.out.println(tipo);
                    consultasql = "Select b.identificacion, b.idjose as 'N Manejo', b.numerofuego as 'N Fuego', b.NumSenasa as 'N Senasa', "
                            + "b.fechaaplicacion as 'Fecha caravaneada', b.sexo as 'Sexo', "
                            + "b.anionacimiento as 'Año Nacimiento', "
                            + "p.descripcion as 'Pelaje', "
                            + "b.ColorCaravana as 'Color caravana'from  bovino b, "
                            + "tipobovino tb, pelaje p "
                            + "where b.idpelaje = p.idpelaje and b.idtipobovino = tb.idtipobovino and b.idtipobovino ='" + tipo + "' and b.idtag <> '' "
                            + "order by idjose";
                }
            }
        }
        return consultasql;

    }

    private void CrearTabla(String sql) {
        try {
            Conectar();
            ResultSet rs = stmt.executeQuery(sql);
            tablaanimales.setModel(modelo);
            tablaanimales.setAutoResizeMode(tablaanimales.AUTO_RESIZE_ALL_COLUMNS);
            ConversorRSaDefaultTableModel.completar(rs, modelo);
            tablaanimales.getColumnModel().getColumn(0).setMaxWidth(0);
            tablaanimales.getColumnModel().getColumn(0).setMinWidth(0);
            tablaanimales.getColumnModel().getColumn(0).setPreferredWidth(0);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Error en la consulta de animales", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    public void mostrarFichaAnimal(java.awt.event.MouseEvent evt) {
        int fila = tablaanimales.rowAtPoint(evt.getPoint());
        int columna = tablaanimales.columnAtPoint(evt.getPoint());
        if ((fila > -1) && (columna > -1)) {
            System.out.println(modelo.getValueAt(fila, columna));
        }

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tablaanimales = new javax.swing.JTable();
        lblMensaje = new javax.swing.JLabel();
        panelFiltros = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        cbFiltroAnimales = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        tfIdentificacion = new javax.swing.JTextField();
        btnImprimir = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Rodeo existente");
        setResizable(false);

        jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 14));
        jLabel1.setText("ANIMALES EXISTENTES");

        tablaanimales.setAutoCreateRowSorter(true);
        tablaanimales.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tablaanimales.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_ALL_COLUMNS);
        tablaanimales.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        tablaanimales.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tablaanimalesMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tablaanimales);
        tablaanimales.getColumnModel().getColumn(0).setResizable(false);
        tablaanimales.getColumnModel().getColumn(1).setResizable(false);
        tablaanimales.getColumnModel().getColumn(3).setResizable(false);

        panelFiltros.setBorder(javax.swing.BorderFactory.createTitledBorder("Aplicar filtro para la busqueda"));

        jLabel3.setText("Filtrar por:");

        cbFiltroAnimales.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Existentes", "Vendidos", "Caravana Amarillo", "Caravana Roja", "Caravana Celeste", "Caravana Naranja", "Caravana Blanca", "Vaca", "Vaquillona", "Ternero", "Toro", "Torito", "Novillo" }));
        cbFiltroAnimales.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbFiltroAnimalesActionPerformed(evt);
            }
        });

        jLabel2.setText("Nº de Manejo");

        tfIdentificacion.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                tfIdentificacionKeyReleased(evt);
            }
        });

        javax.swing.GroupLayout panelFiltrosLayout = new javax.swing.GroupLayout(panelFiltros);
        panelFiltros.setLayout(panelFiltrosLayout);
        panelFiltrosLayout.setHorizontalGroup(
            panelFiltrosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelFiltrosLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(cbFiltroAnimales, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(92, 92, 92)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(tfIdentificacion, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(248, Short.MAX_VALUE))
        );
        panelFiltrosLayout.setVerticalGroup(
            panelFiltrosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelFiltrosLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelFiltrosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(cbFiltroAnimales, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(tfIdentificacion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        btnImprimir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/Impresora.png"))); // NOI18N
        btnImprimir.setText("Imprimir listado de animales");
        btnImprimir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnImprimirActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(291, 291, 291)
                .addComponent(jLabel1)
                .addGap(323, 323, 323))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 751, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnImprimir, javax.swing.GroupLayout.PREFERRED_SIZE, 257, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 132, Short.MAX_VALUE)
                .addComponent(lblMensaje, javax.swing.GroupLayout.PREFERRED_SIZE, 362, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(panelFiltros, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(11, 11, 11)
                .addComponent(jLabel1)
                .addGap(9, 9, 9)
                .addComponent(panelFiltros, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(20, 20, 20)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 208, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblMensaje, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnImprimir))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-787)/2, (screenSize.height-421)/2, 787, 421);
    }// </editor-fold>//GEN-END:initComponents

private void tablaanimalesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablaanimalesMouseClicked
    if (evt.getButton() == java.awt.event.MouseEvent.BUTTON1) {
        int fila = tablaanimales.getSelectedRow();
        String id = String.valueOf(tablaanimales.getValueAt(fila, 1));
        FichaAnimal F = new FichaAnimal(id);
        F.setVisible(true);
        DefaultTableModel modelo = new DefaultTableModel();
        tablaanimales.setModel(modelo);
        CrearTabla(DefinirConsultaSQL());
    }
    /*
    if (evt.getButton() == java.awt.event.MouseEvent.BUTTON1) {
    ninja = true;
    }
    if (ninja) {
    int fila = tablaanimales.rowAtPoint(evt.getPoint());
    int columna = 0; //tablaanimales.columnAtPoint(evt.getPoint());       
    if ((fila > -1) && (columna == 0)) {
    idsenasa = String.valueOf(modelo.getValueAt(fila, columna));
    MenuFichaAnimal.show(tablaanimales, evt.getX(), evt.getY());
    }
    ninja = false;
    }*/
}//GEN-LAST:event_tablaanimalesMouseClicked

private void cbFiltroAnimalesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbFiltroAnimalesActionPerformed
    String consulta = DefinirConsultaSQL();
    tfIdentificacion.setText("");
    CrearTabla(consulta);
    lblMensaje.setText("La cantidad de animales es: " + tablaanimales.getRowCount());
}//GEN-LAST:event_cbFiltroAnimalesActionPerformed

    private void tfIdentificacionKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfIdentificacionKeyReleased
        String consulta = "Select b.identificacion, b.idjose as 'Num. Manejo',"
                + " b.numerofuego as 'Num. Fuego', b.NumSenasa as 'Num. Senasa', "
                + "b.fechaaplicacion as 'Fecha caravaneada', b.sexo as 'Sexo',"
                + " b.anionacimiento as 'Año Nacimiento', p.descripcion as"
                + " 'Pelaje', b.ColorCaravana as 'Color caravana' from"
                + "  bovino b, tipobovino tb, pelaje p where "
                + "b.idjose LIKE '%" + tfIdentificacion.getText().trim() + "' and b.idpelaje = p.idpelaje and b.idtipobovino = tb.idtipobovino";



        CrearTabla(consulta);
        lblMensaje.setText("La cantidad de animales es: " + String.valueOf(tablaanimales.getRowCount()));

    }//GEN-LAST:event_tfIdentificacionKeyReleased

    private void btnImprimirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnImprimirActionPerformed
        try {
            new MetodosImpresion().ReporteAnimales();
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(AnimalesExistentes.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(AnimalesExistentes.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_btnImprimirActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(AnimalesExistentes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AnimalesExistentes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AnimalesExistentes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AnimalesExistentes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new AnimalesExistentes().setVisible(true);
            }
        });
    }
    DefaultTableModel modelo = new DefaultTableModel();
    private conexion db;
    private Statement stmt;
    private String idsenasa;
    private boolean ninja = false;
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnImprimir;
    private javax.swing.JComboBox cbFiltroAnimales;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblMensaje;
    private javax.swing.JPanel panelFiltros;
    private javax.swing.JTable tablaanimales;
    private javax.swing.JTextField tfIdentificacion;
    // End of variables declaration//GEN-END:variables
}
